package com.comac.tasks.manager.app.gatewayimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.cola.logger.Logger;
import com.alibaba.cola.logger.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.tasks.manager.app.common.enums.DealTypeEnum;
import com.comac.tasks.manager.app.common.enums.OrderRuleEnum;
import com.comac.tasks.manager.app.common.enums.ProcessTypeEnum;
import com.comac.tasks.manager.app.domain.gateway.TasksManagerGateway;
import com.comac.tasks.manager.app.dto.*;
import com.comac.tasks.manager.app.gatewayimpl.database.TasksManagerTodoMapper;
import com.comac.tasks.manager.app.gatewayimpl.database.dataobject.TasksManagerTodoDO;
import com.comac.tasks.manager.app.utils.CustomSnowflake;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * TasksManagerGatewayImpl
 *
 * @author wfb
 * @date 2021年11月9日15:39:18
 */
@Component
@Slf4j
public class TasksManagerGatewayImpl implements TasksManagerGateway {
    private static Logger logger = LoggerFactory.getLogger(TasksManagerGatewayImpl.class);


    @Autowired
    private TasksManagerTodoMapper tasksManagerTodoMapper;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

//    @Autowired
//    private TasksManagerConverter tasksManagerConverter;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response insert(TasksManagerDTO dto) {
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        BeanUtils.copyProperties(dto, tasksManagerTodoDO);
        tasksManagerTodoDO.setId(CustomSnowflake.nextId());
        if (null != dto.getFieldArea()) {
            tasksManagerTodoDO.setFieldArea(JSONObject.toJSONString(dto.getFieldArea()));
        }
        tasksManagerTodoDO.setDeleteFlag("0");
        if (StringUtils.isNotBlank(dto.getCreateTime())) {
            tasksManagerTodoDO.setCreateTime(DateUtil.parseDateTime(dto.getCreateTime()));
        }
        if (StringUtils.isNotBlank(dto.getExpectedCompletionTime())) {
            tasksManagerTodoDO.setExpectedCompletionTime(DateUtil.parseDateTime(dto.getExpectedCompletionTime()));
        }
        if (StringUtils.isNotBlank(dto.getProcessCreateTime())) {
            tasksManagerTodoDO.setProcessCreateTime(DateUtil.parseDateTime(dto.getProcessCreateTime()));
        }
        try {
            tasksManagerTodoMapper.insert(tasksManagerTodoDO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("insert error msg:" + e.toString());
            logger.error("insert stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("插入代办事项异常！");
        }
        logger.info("创建流程代办事项成功=======:"+ tasksManagerTodoDO);
        return Response.buildSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response batchInsert(TasksManagerBatchInsertDTO batchInsertDTO) {
        List<TasksManagerTodoDO> todoDOS = new ArrayList<>();
        List<TasksManagerBatchDTO> managerBatchDTOS = batchInsertDTO.getTasksManagerDTOS().stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(f -> f.getTaskInstanceId() + f.getProcessInstanceId() + f.getOperator()))), ArrayList::new));
        managerBatchDTOS.stream().forEach(e -> {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("TASK_INSTANCE_ID", e.getTaskInstanceId());
            wrapper.eq("PROCESS_INSTANCE_ID", e.getProcessInstanceId());
            wrapper.eq("operator", e.getOperator());
            List<TasksManagerTodoDO> todoDOList = tasksManagerTodoMapper.selectList(wrapper);
            if (CollectionUtils.isEmpty(todoDOList)) {
                TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
                BeanUtils.copyProperties(e, tasksManagerTodoDO);
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException interruptedException) {
//                    interruptedException.printStackTrace();
//                    logger.error("interruptedException error msg:" + interruptedException.toString());
//                    logger.error("interruptedException stackTrace:" + Arrays.toString(interruptedException.getStackTrace()));
//                }
//                String id = DateUtil.format(new Date(), "yyMMddHHmmssSSSSS");
                tasksManagerTodoDO.setId(CustomSnowflake.nextId());
                if (null != e.getFieldArea()) {
                    tasksManagerTodoDO.setFieldArea(JSONObject.toJSONString(e.getFieldArea()));
                }
                tasksManagerTodoDO.setDeleteFlag("0");
                tasksManagerTodoDO.setInsertTime(new Date());
                if (StringUtils.isNotBlank(e.getCreateTime())) {
                    tasksManagerTodoDO.setCreateTime(DateUtil.parseDateTime(e.getCreateTime()));
                }
                // 应完成时间
                if (StringUtils.isNotBlank(e.getExpectedCompletionTime())) {
                    tasksManagerTodoDO.setExpectedCompletionTime(DateUtil.parseDateTime(e.getExpectedCompletionTime()));
                }
                // 流程发起时间
                if (StringUtils.isNotBlank(e.getProcessCreateTime())) {
                    tasksManagerTodoDO.setProcessCreateTime(DateUtil.parseDateTime(e.getProcessCreateTime()));
                }
                // 待办任务设置的预警时间
                if (StringUtils.isNotBlank(e.getWarningTime())) {
                    tasksManagerTodoDO.setWarningTime(DateUtil.parseDateTime(e.getWarningTime()));
                }
                todoDOS.add(tasksManagerTodoDO);
            } else {
                logger.info("batchInsert：过滤重复任务id和流程实例id：,TASK_INSTANCE_ID:" + e.getTaskInstanceId() + ",PROCESS_INSTANCE_ID" + e.getProcessInstanceId());
            }
        });
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        TasksManagerTodoMapper mapper = session.getMapper(TasksManagerTodoMapper.class);
        try {
            for (int i = 0; i < todoDOS.size(); i++) {
                mapper.insert(todoDOS.get(i));
                if (i % 1000 == 999 || i == managerBatchDTOS.size() - 1) {
                    session.commit();
                    session.clearCache();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("insert error msg:" + e.toString());
            logger.error("insert stackTrace:" + Arrays.toString(e.getStackTrace()));
            session.rollback();
            throw new BizException("批量插入代办事项异常！");
        } finally {
            session.close();
        }
        logger.info("批量创建流程代办事项成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return Response.buildSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response batchInsertPerformance(TasksManagerBatchInsertDTO batchInsertDTO) {
        List<TasksManagerBatchDTO> managerBatchDTOS = batchInsertDTO.getTasksManagerDTOS().stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(f -> f.getTaskInstanceId() + f.getProcessInstanceId() + f.getOperator()))), ArrayList::new));

        List<String> taskInstanceIdList = managerBatchDTOS.stream().map(TasksManagerBatchDTO::getTaskInstanceId).collect(Collectors.toList());
        List<String> processInstanceIdList = managerBatchDTOS.stream().map(TasksManagerBatchDTO::getProcessInstanceId).collect(Collectors.toList());
        List<String> operatorList = managerBatchDTOS.stream().map(TasksManagerBatchDTO::getOperator).collect(Collectors.toList());

        LambdaQueryWrapper<TasksManagerTodoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TasksManagerTodoDO::getTaskInstanceId, taskInstanceIdList);
        queryWrapper.in(TasksManagerTodoDO::getProcessInstanceId, processInstanceIdList);
        queryWrapper.in(TasksManagerTodoDO::getOperator, operatorList);
        List<TasksManagerTodoDO> existedTodoDOList = tasksManagerTodoMapper.selectList(queryWrapper);

        List<String> existedTaskInstanceIdList = existedTodoDOList.stream().map(TasksManagerTodoDO::getTaskInstanceId).collect(Collectors.toList());
        List<String> existedProcessInstanceIdList = existedTodoDOList.stream().map(TasksManagerTodoDO::getProcessInstanceId).collect(Collectors.toList());
        List<String> existedOperatorList = existedTodoDOList.stream().map(TasksManagerTodoDO::getOperator).collect(Collectors.toList());

        List<TasksManagerTodoDO> todoDOS = managerBatchDTOS.stream()
                .filter(task -> !existedTaskInstanceIdList.contains(task.getTaskInstanceId()))
                .filter(task -> !existedProcessInstanceIdList.contains(task.getProcessInstanceId()))
                .filter(task -> !existedOperatorList.contains(task.getOperator()))
                .map(this::insertDoPrepare)
                .collect(Collectors.toList());

        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        TasksManagerTodoMapper mapper = session.getMapper(TasksManagerTodoMapper.class);
        try {
            for (int i = 0; i < todoDOS.size(); i++) {
                mapper.insert(todoDOS.get(i));
                if (i % 1000 == 999 || i == managerBatchDTOS.size() - 1) {
                    session.commit();
                    session.clearCache();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("insert error msg:" + e.toString());
            logger.error("insert stackTrace:" + Arrays.toString(e.getStackTrace()));
            session.rollback();
            throw new BizException("批量插入代办事项异常！");
        } finally {
            session.close();
        }
        logger.info("批量创建流程代办事项成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return Response.buildSuccess();
    }

    private TasksManagerTodoDO insertDoPrepare(TasksManagerBatchDTO batchDto) {
        TasksManagerTodoDO toDoTask = new TasksManagerTodoDO();
        BeanUtils.copyProperties(batchDto, toDoTask);
        toDoTask.setId(CustomSnowflake.nextId());
        if (null != batchDto.getFieldArea()) {
            toDoTask.setFieldArea(JSONObject.toJSONString(batchDto.getFieldArea()));
        }
        toDoTask.setDeleteFlag("0");
        toDoTask.setInsertTime(new Date());
        if (StringUtils.isNotBlank(batchDto.getCreateTime())) {
            toDoTask.setCreateTime(DateUtil.parseDateTime(batchDto.getCreateTime()));
        }
        // 应完成时间
        if (StringUtils.isNotBlank(batchDto.getExpectedCompletionTime())) {
            toDoTask.setExpectedCompletionTime(DateUtil.parseDateTime(batchDto.getExpectedCompletionTime()));
        }
        // 流程发起时间
        if (StringUtils.isNotBlank(batchDto.getProcessCreateTime())) {
            toDoTask.setProcessCreateTime(DateUtil.parseDateTime(batchDto.getProcessCreateTime()));
        }
        // 待办任务设置的预警时间
        if (StringUtils.isNotBlank(batchDto.getWarningTime())) {
            toDoTask.setWarningTime(DateUtil.parseDateTime(batchDto.getWarningTime()));
        }
        return toDoTask;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateStatus(TasksManagerUpDTO tasksManagerUpDTO) {
        if (ProcessTypeEnum.RUSH_TO_SIGN.getCode().equals(tasksManagerUpDTO.getType())) {
            return this.rushToSign(tasksManagerUpDTO);
        }
        if (ProcessTypeEnum.JOINTLY_SIGN.getCode().equals(tasksManagerUpDTO.getType())) {
            return this.jointlySign(tasksManagerUpDTO);
        }
        if (ProcessTypeEnum.CLOSE.getCode().equals(tasksManagerUpDTO.getType())) {
            return this.cloneOrOpenProcess(tasksManagerUpDTO);
        }
        return Response.buildFailure("3001", "类型不存在");
    }

    /**
     * "
     * 关闭或启用流程：根据流程实例id和来源应用编码参数进行关闭和启用当前流程。关闭时process_node_status传CANCEL，启用是把流程状态更新为NORMAL即可
     *
     * @param tasksManagerUpDTO
     * @return
     */
    private Response cloneOrOpenProcess(TasksManagerUpDTO tasksManagerUpDTO) {
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper();
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        if (!CollectionUtils.isEmpty(tasksManagerUpDTO.getProcessInstanceIds())) {
            updateWrapper.in("PROCESS_INSTANCE_ID", tasksManagerUpDTO.getProcessInstanceIds());
        } else {
            throw new BizException("流程实例id不能为空！");
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getSourceApplicationNum())) {
            updateWrapper.eq("SOURCE_APPLICATION_NUM", tasksManagerUpDTO.getSourceApplicationNum());
        } else {
            throw new BizException("来源应用编码不能为空！");
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getStatus())) {
            tasksManagerTodoDO.setStatus(tasksManagerUpDTO.getStatus());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getProcessNodeStatus())) {
            tasksManagerTodoDO.setProcessNodeStatus(tasksManagerUpDTO.getProcessNodeStatus());
        }
        tasksManagerTodoDO.setUpdateTime(new Date());
        //查询是否有待办任务
        List<TasksManagerTodoDO> tasksManagerTodo = tasksManagerTodoMapper.selectList(updateWrapper);
        logger.info("需要关闭任务tasksManagerTodo:"+JSONObject.toJSONString(tasksManagerTodo));
        if (tasksManagerTodo.isEmpty()) {
            throw new BizException("关闭任务未查询到数据");
        }
        try {
            //更新代办状态
            tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
            logger.info("关闭流程完成，tasksManagerTodoDO:"+JSONObject.toJSONString(tasksManagerTodoDO));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("closeFlow error msg:" + e.toString());
            logger.error("closeFlow stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("关闭流程事项状态异常 !");
        }
        logger.info("关闭流程代办事项成功=======:"+ JSONObject.toJSONString(tasksManagerTodoDO));
        return Response.buildSuccess();
    }

    /**
     * "
     * 会签逻辑：当flag为true时说明会签已结束，会根据传入的任务id 删掉所有状态为TODO的任务。
     * 当flag为false时说明会签还没结束，会根据传入的任务id和流程实例id更新状态。
     * <p>
     * 例：如果10个人参与会签 8个人完成即结束的话 flag为false正常更新完8个人的任务，然后flag为true再掉一次更新接口。
     * 如果10个人参与会签 10个人完成即结束的话 flag为false正常更新完10个人的任务，然后flag为true再掉一次更新接口。
     *
     * @param tasksManagerUpDTO
     * @return
     */
    private Response jointlySign(TasksManagerUpDTO tasksManagerUpDTO) {
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper();
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        if (!CollectionUtils.isEmpty(tasksManagerUpDTO.getTaskInstanceIds())) {
            updateWrapper.in("TASK_INSTANCE_ID", tasksManagerUpDTO.getTaskInstanceIds());
        }
        if (!CollectionUtils.isEmpty(tasksManagerUpDTO.getProcessInstanceIds())) {
            updateWrapper.in("PROCESS_INSTANCE_ID", tasksManagerUpDTO.getProcessInstanceIds());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getOperator())) {
            updateWrapper.eq("operator", tasksManagerUpDTO.getOperator());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getOperatorName())) {
            updateWrapper.eq("OPERATOR_NAME", tasksManagerUpDTO.getOperatorName());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getStatus())) {
            tasksManagerTodoDO.setStatus(tasksManagerUpDTO.getStatus());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getProcessNodeStatus())) {
            tasksManagerTodoDO.setProcessNodeStatus(tasksManagerUpDTO.getProcessNodeStatus());
        }
        tasksManagerTodoDO.setUpdateTime(new Date());
        //查询是否有待办任务
        List<TasksManagerTodoDO> tasksManagerTodo = tasksManagerTodoMapper.selectList(updateWrapper);
        logger.info("查询会签所有人的任务tasksManagerTodo:"+ JSONObject.toJSONString(tasksManagerTodo));
        if (tasksManagerTodo.isEmpty()) {
            throw new BizException("会签流程代办更新状态未查询到数据");
        }
        //结束节点是true时 说明待办节点已结束
        if (tasksManagerUpDTO.getFlag()) {
            try {
                List<Long> idsList = tasksManagerTodo.stream().filter(e -> StringUtils.equals("TODO", e.getStatus())).map(TasksManagerTodoDO::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(idsList)) {
                    if(!StringUtils.isEmpty(tasksManagerUpDTO.getProcessNodeStatus())&&tasksManagerUpDTO.getProcessNodeStatus().equals("ROLLBACK")&&!StringUtils.isEmpty(tasksManagerUpDTO.getCurrentTaskId())){
                       // 驳回时更新操作人记录，否则直接删除所有待办的话在已办里面查不到该操作人的驳回记录
                        UpdateWrapper<TasksManagerTodoDO> updateWrapperExt = new UpdateWrapper();
                        updateWrapperExt.eq("TASK_INSTANCE_ID", tasksManagerUpDTO.getCurrentTaskId());
                        // 不删除当前任务项
                        idsList.remove(tasksManagerTodo.stream().filter(e -> StringUtils.equals(tasksManagerUpDTO.getCurrentTaskId(), e.getTaskInstanceId())).collect(Collectors.toList()).get(0).getId());
                        // 更新任务状态
                        tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapperExt);
                        logger.info("驳回时更新操作人记录:"+JSONObject.toJSONString(tasksManagerTodoDO));
                    }
                    //会签当流程结束时筛选出所有的状态为TODO的待办删掉
                    if(!idsList.isEmpty()){
                        logger.info("删除待办开始tasksManagerTodo:"+JSONObject.toJSONString(idsList));
                        tasksManagerTodoMapper.deleteBatchIds(idsList);
                        logger.info("删除待办结束idsList:"+JSONObject.toJSONString(idsList));
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("delete stackTrace:" + Arrays.toString(e.getStackTrace()));
                throw new BizException("批量删除状态为TODO状态的待办异常");
            }
        }
        //当流程节点为false时，会签说明还没有结束，继续更新状态
        if (!tasksManagerUpDTO.getFlag()) {
            try {
                //更新代办状态
                tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
                logger.info("更新会签完成,tasksManagerTodoDO:"+JSONObject.toJSONString(tasksManagerTodoDO));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("jointlySign stackTrace:" + Arrays.toString(e.getStackTrace()));
                throw new BizException("更新会签代办事项状态异常 !");
            }
        }
        return Response.buildSuccess();
    }

    /**
     * "
     * 抢签逻辑：
     * 例：如果10个人参与抢签 1个人完成即结束的话 。把所有参与抢签的任务id作为参数给我，并把抢签成功的operator传进来
     * 程序会把operator的那个人状态更新掉，然后删掉其他参与抢签的9个人的任务。抢签对flag不做处理。
     *
     * @param tasksManagerUpDTO
     * @return
     */
    private Response rushToSign(TasksManagerUpDTO tasksManagerUpDTO) {
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper();
        UpdateWrapper<TasksManagerTodoDO> updateWrapperExt = new UpdateWrapper();
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        if (!CollectionUtils.isEmpty(tasksManagerUpDTO.getTaskInstanceIds())) {
            updateWrapper.in("TASK_INSTANCE_ID", tasksManagerUpDTO.getTaskInstanceIds());
            updateWrapperExt.in("TASK_INSTANCE_ID", tasksManagerUpDTO.getTaskInstanceIds());
        }
        if (!CollectionUtils.isEmpty(tasksManagerUpDTO.getProcessInstanceIds())) {
            updateWrapper.in("PROCESS_INSTANCE_ID", tasksManagerUpDTO.getProcessInstanceIds());
            updateWrapperExt.in("PROCESS_INSTANCE_ID", tasksManagerUpDTO.getProcessInstanceIds());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getOperator())) {
            updateWrapper.eq("operator", tasksManagerUpDTO.getOperator());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getOperatorName())) {
            updateWrapper.eq("OPERATOR_NAME", tasksManagerUpDTO.getOperatorName());
        }

        if (StringUtils.isNotBlank(tasksManagerUpDTO.getStatus())) {
            tasksManagerTodoDO.setStatus(tasksManagerUpDTO.getStatus());
        }
        if (StringUtils.isNotBlank(tasksManagerUpDTO.getProcessNodeStatus())) {
            tasksManagerTodoDO.setProcessNodeStatus(tasksManagerUpDTO.getProcessNodeStatus());
        }
        tasksManagerTodoDO.setUpdateTime(new Date());
        //查询出所有参与抢签的人员
        List<TasksManagerTodoDO> todoDOList = tasksManagerTodoMapper.selectList(updateWrapperExt);
        logger.info("查询实例id单条件下的所有的待办事项：{}"+JSONObject.toJSONString(todoDOList));
        //筛选出所有参与抢签人的id
        List<Long> integerListExt = todoDOList.stream().map(TasksManagerTodoDO::getId).collect(Collectors.toList());
        //查询出抢签成功的那个人
        List<TasksManagerTodoDO> tasksManagerTodo = tasksManagerTodoMapper.selectList(updateWrapper);
        if (tasksManagerTodo.isEmpty()) {
            throw new BizException("抢签流程代办更新状态未查询到数据");
        }
        logger.info("查询操作人员的待办事项：:"+JSONObject.toJSONString(tasksManagerTodo));
        //筛选出抢签成功的那个人的id
        List<Long> integerList = tasksManagerTodo.stream().map(TasksManagerTodoDO::getId).collect(Collectors.toList());
        //把抢签未成功的人的id筛选处理
        List<Long> listIds = integerListExt.stream().filter(e -> !integerList.contains(e)).collect(Collectors.toList());
        try {
            //更新代办状态
            if (null != tasksManagerTodoDO) {
                //更新抢签成功
                tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
            }
            //代办表逻辑删除
            if (!CollectionUtils.isEmpty(listIds)) {
                tasksManagerTodoMapper.deleteBatchIds(listIds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("rushToSign error msg:" + e.toString());
            logger.error("rushToSign stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("更新抢签代办事项状态异常 !");
        }
        logger.info("修改抢签流程代办事项成功:"+JSONObject.toJSONString(tasksManagerTodoDO));
        return Response.buildSuccess();
    }

    @Override
    public PageResponse selectPage(TasksManagerQry qry) {
        QueryWrapper<TasksManagerTodoDO> queryWrapper = new QueryWrapper();
        if (CollectionUtil.isNotEmpty(qry.getAppCodes())) {
            queryWrapper.in("APP_CODE", qry.getAppCodes());
        }
        if (CollectionUtil.isNotEmpty(qry.getNeAppCodes())) {
            // 遍历neAppCodes列表，添加不等于条件
//            for (String appCode : qry.getNeAppCodes()) {
//                queryWrapper.ne("APP_CODE", appCode);
//            }
//            queryWrapper.or().isNull("APP_CODE");
//            queryWrapper.isNotNull("APP_CODE");

            queryWrapper.and(
                    i ->
                            i.notIn("APP_CODE", qry.getNeAppCodes())
                                    .or()
                                    .isNull("APP_CODE")
            );

        }
        if (StringUtils.isNotBlank(qry.getOperator())) {
            queryWrapper.eq("OPERATOR", qry.getOperator());
        }
        if (StringUtils.isNotBlank(qry.getCreator())) {
            queryWrapper.eq("CREATOR", qry.getCreator());
        }
        if (StringUtils.isNotBlank(qry.getOperatorName())) {
            queryWrapper.eq("OPERATOR_NAME", qry.getOperatorName());
        }
        if (StringUtils.isNotBlank(qry.getProcessCode())) {
            queryWrapper.eq("PROCESS_CODE", qry.getProcessCode());
        }
        if (StringUtils.isNotBlank(qry.getProcessInstanceName())) {
            queryWrapper.like("PROCESS_INSTANCE_NAME", qry.getProcessInstanceName());
        }
        if (StringUtils.isNotBlank(qry.getSourceApplicationName())) {
            queryWrapper.like("SOURCE_APPLICATION_NAME", qry.getSourceApplicationName());
        }

        if (StringUtils.isNotBlank(qry.getTasksContent())) {
            queryWrapper.like("TASKS_CONTENT", qry.getTasksContent());
        }
        if (StringUtils.isNotBlank(qry.getSourceApplicationNum()) && StringUtils.equals("CMOS", qry.getSourceApplicationNum())) {
            queryWrapper.and(i -> i.eq("SOURCE_APPLICATION_NUM", "CMOS").or().eq("SOURCE_APPLICATION_NUM", "CMOS2"));
        } else if (StringUtils.isNotBlank(qry.getSourceApplicationNum())) {
            queryWrapper.eq("SOURCE_APPLICATION_NUM", qry.getSourceApplicationNum());
        }
        // 添加流程实例ID查询条件
        if (null != qry.getProcessInstanceId()) {
            queryWrapper.eq("PROCESS_INSTANCE_ID", qry.getProcessInstanceId());
        }
        if (null != qry.getTaskInstanceId()) {
            queryWrapper.eq("TASK_INSTANCE_ID", qry.getTaskInstanceId());
        }
        if (null != qry.getCreateTimeStart()) {
            queryWrapper.ge("CREATE_TIME", qry.getCreateTimeStart());
        }
        if (null != qry.getCreateTimeEnd()) {
            queryWrapper.le("CREATE_TIME", qry.getCreateTimeEnd());
        }
        //状态查询
        if (DealTypeEnum.TODO.getCode().equals(qry.getStatus())) {
            queryWrapper.eq("PROCESS_NODE_STATUS", "NORMAL");
            queryWrapper.in("STATUS", Arrays.asList("TODO"));
        } else if (DealTypeEnum.DONE.getCode().equals(qry.getStatus())) {
            // 区分应用系统
            if (StringUtils.isNotBlank(qry.getSourceApplicationNum()) &&
                    StringUtils.equals("MOM2", qry.getSourceApplicationNum())) {
                queryWrapper.eq("PROCESS_NODE_STATUS", "NORMAL");
                queryWrapper.in("STATUS", Arrays.asList("DONE"));
            } else {
                queryWrapper.and(i -> i.or().or(a -> a.eq("PROCESS_NODE_STATUS", "NORMAL").eq("STATUS", "DONE")).
                        or().or(j -> j.eq("PROCESS_NODE_STATUS", "ROLLBACK").eq("STATUS", "DONE")).
                        or().or(j -> j.eq("PROCESS_NODE_STATUS", "END").eq("STATUS", "DONE")));
            }
        } else if (DealTypeEnum.RECALL.getCode().equals(qry.getStatus())) {
            queryWrapper.and(i -> i.in("PROCESS_NODE_STATUS", Arrays.asList("END", "CANCEL", "ROLLBACK", "REJECT", "RECALL")).
                    in("STATUS", Arrays.asList("END", "CANCEL", "ROLLBACK", "REJECT", "RECALL")));
        } else {
            queryWrapper.and(a -> a.in("PROCESS_NODE_STATUS", Arrays.asList("NORMAL", "END", "CANCEL", "ROLLBACK", "REJECT", "RECALL"))
                    .in("STATUS", Arrays.asList("TODO", "DONE", "END", "CANCEL", "ROLLBACK", "REJECT", "RECALL")));
        }

        if (StringUtils.isNotBlank(qry.getCreateNameOrCode())) {
            queryWrapper.and(q -> q.like("CREATOR", qry.getCreateNameOrCode()).
                    or().like("CREATOR_NAME", qry.getCreateNameOrCode()));
        }
        //门户参数
        if (null != qry.getCreateTime() && null != qry.getCreateTime().getStartTime()) {
            queryWrapper.ge("CREATE_TIME", DateUtil.beginOfDay(LocalDateToUdate(qry.getCreateTime().getStartTime())));
        }
        if (null != qry.getCreateTime() && null != qry.getCreateTime().getEndTime()) {
            queryWrapper.le("CREATE_TIME", DateUtil.endOfDay(LocalDateToUdate(qry.getCreateTime().getEndTime())));
        }
        if (null != qry.getProcessCreateTime() && null != qry.getProcessCreateTime().getStartTime()) {
            queryWrapper.ge("PROCESS_CREATE_TIME", DateUtil.beginOfDay(LocalDateToUdate(qry.getProcessCreateTime().getStartTime())));
        }
        if (null != qry.getProcessCreateTime() && null != qry.getProcessCreateTime().getEndTime()) {
            queryWrapper.le("PROCESS_CREATE_TIME", DateUtil.endOfDay(LocalDateToUdate(qry.getProcessCreateTime().getEndTime())));
        }
        if (StringUtils.isNotBlank(qry.getProcessName())) {
            queryWrapper.like("PROCESS_NAME", qry.getProcessName());
        }
        if (StringUtils.isNotBlank(qry.getBusinessCode())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessCode());
        }
        if (StringUtils.isNotBlank(qry.getBusinessTypes())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessTypes());
        }
        if (StringUtils.isNotBlank(qry.getBusinessStatus())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessStatus());
        }
        if (StringUtils.isNotBlank(qry.getBusinessName())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessName());
        }
        if (StringUtils.isNotBlank(qry.getModelName())) {
            queryWrapper.like("FIELD_AREA", qry.getModelName());
        }
        if (StringUtils.isNotBlank(qry.getModelKey())) {
            queryWrapper.like("FIELD_AREA", qry.getModelKey());
        }
        if (StringUtils.isNotBlank(qry.getToDoContent())) {
            queryWrapper.like("FIELD_AREA", qry.getToDoContent());
        }
        if (StringUtils.isNotBlank(qry.getNodeName())) {
            queryWrapper.like("NODE_NAME", qry.getNodeName());
        }

        // 添加待办任务所属业务模块查询条件
        if (CollectionUtil.isNotEmpty(qry.getBusinessModuleCodes())) {
            queryWrapper.in("BUSINESS_MODULE_CODE", qry.getBusinessModuleCodes());
        }

        // 添加待办任务所属业务表单模块查询条件
        if (CollectionUtil.isNotEmpty(qry.getFormModuleCodes())) {
            queryWrapper.in("FORM_MODULE_CODE", qry.getFormModuleCodes());
        }

        //1、默认排序规则：创建时间倒序
        //2、增加创建时间和应完时间选项create_time和expected_completion_time
        // 业务侧前端，需要支持俩个时间排序的选项，待办组件后端需要添加1、排序字段 2、排序规则（倒序还是正序）
        if (StringUtils.isNotBlank(qry.getOrderByClause()) &&
                StringUtils.isNotBlank(qry.getOrderByRule())) {
            // 如果需要排序并且按照正序进行排序
            if (qry.getOrderByRule().equalsIgnoreCase(OrderRuleEnum.ASC.getCode())) {
                queryWrapper.orderByAsc("" + qry.getOrderByClause() + "");
            } else if (qry.getOrderByRule().equalsIgnoreCase(OrderRuleEnum.DESC.getCode())) {// 按照规则降序排列
                queryWrapper.orderByDesc("" + qry.getOrderByClause() + "");
            } else {
                queryWrapper.orderByDesc("CREATE_TIME");
            }
        } else { // 否则,默认就按照创建时间倒序
            queryWrapper.orderByDesc("CREATE_TIME");
        }
        Page page = new Page(qry.getPageNum(), qry.getPageSize());
        Page managerDOPage = null;
        try {
            managerDOPage = tasksManagerTodoMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("selectPage error msg:" + e.toString());
            logger.error("selectPage stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("分页查询代办消息异常");
        }
        logger.info("分页查询流程代办列表成功=======:"+JSONObject.toJSONString(managerDOPage.getRecords()));
        return PageResponse.successPage(managerDOPage);
    }

    @Override
    public PageResponse selectPageByCreator(TasksManagerQry qry) {
        QueryWrapper<TasksManagerTodoDO> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(qry.getCreator())) {
            queryWrapper.eq("CREATOR", qry.getCreator());
        }
        queryWrapper.and(a -> a.in("PROCESS_NODE_STATUS", Arrays.asList("NORMAL", "END", "CANCEL", "ROLLBACK", "REJECT", "RECALL"))
                .in("STATUS", Arrays.asList("TODO", "DONE", "END", "CANCEL", "ROLLBACK", "REJECT", "RECALL")));
        //queryWrapper.groupBy("PROCESS_INSTANCE_ID");
        //门户参数
        if (null != qry.getCreateTime() && null != qry.getCreateTime().getStartTime()) {
            queryWrapper.ge("CREATE_TIME", DateUtil.beginOfDay(LocalDateToUdate(qry.getCreateTime().getStartTime())));
        }
        if (null != qry.getCreateTime() && null != qry.getCreateTime().getEndTime()) {
            queryWrapper.le("CREATE_TIME", DateUtil.endOfDay(LocalDateToUdate(qry.getCreateTime().getEndTime())));
        }
        if (null != qry.getProcessCreateTime() && null != qry.getProcessCreateTime().getStartTime()) {
            queryWrapper.ge("PROCESS_CREATE_TIME", DateUtil.beginOfDay(LocalDateToUdate(qry.getProcessCreateTime().getStartTime())));
        }
        if (null != qry.getProcessCreateTime() && null != qry.getProcessCreateTime().getEndTime()) {
            queryWrapper.le("PROCESS_CREATE_TIME", DateUtil.endOfDay(LocalDateToUdate(qry.getProcessCreateTime().getEndTime())));
        }
        if (StringUtils.isNotBlank(qry.getSourceApplicationNum())) {
            queryWrapper.eq("SOURCE_APPLICATION_NUM", qry.getSourceApplicationNum());
        }
        if (StringUtils.isNotBlank(qry.getBusinessCode())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessCode());
        }
        if (StringUtils.isNotBlank(qry.getBusinessTypes())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessTypes());
        }
        if (StringUtils.isNotBlank(qry.getBusinessStatus())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessStatus());
        }
        if (StringUtils.isNotBlank(qry.getBusinessName())) {
            queryWrapper.like("FIELD_AREA", qry.getBusinessName());
        }
        if (StringUtils.isNotBlank(qry.getToDoContent())) {
            queryWrapper.like("FIELD_AREA", qry.getToDoContent());
        }
        if (StringUtils.isNotBlank(qry.getModelName())) {
            queryWrapper.like("FIELD_AREA", qry.getModelName());
        }
        if (StringUtils.isNotBlank(qry.getModelKey())) {
            queryWrapper.like("FIELD_AREA", qry.getModelKey());
        }
        if (StringUtils.isNotBlank(qry.getNodeName())) {
            queryWrapper.like("NODE_NAME", qry.getNodeName());
        }
        if (StringUtils.isNotBlank(qry.getTasksContent())) {
            queryWrapper.like("TASKS_CONTENT", qry.getTasksContent());
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        List<TasksManagerTodoDO> filerList = new ArrayList<>();
        List<TasksManagerTodoDO> managerTodoDOS = new ArrayList<>();
        try {
            List<TasksManagerTodoDO> todoDOS = tasksManagerTodoMapper.selectList(queryWrapper);
            Map<String, TasksManagerTodoDO> latestStations = todoDOS.parallelStream().collect(Collectors.toMap(TasksManagerTodoDO::getProcessInstanceId, Function.identity(), (c1, c2) -> c1.getCreateTime().getTime() < c2.getCreateTime().getTime() ? c1 : c2));
            latestStations.entrySet().stream().forEach(e -> {
                TasksManagerTodoDO value = e.getValue();
                filerList.add(value);
            });
            managerTodoDOS = filerList.stream().sorted((Comparator.comparing(TasksManagerTodoDO::getCreateTime).reversed())).collect(Collectors.toList());
            managerTodoDOS = managerTodoDOS.stream().skip((qry.getPageNum() - 1) * qry.getPageSize()).
                    limit(qry.getPageSize()).collect(Collectors.toList());
            logger.info("分页查询流程代办列表成功======={}",JSONObject.toJSONString(filerList));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("selectPage error msg:" + e.toString());
            logger.error("selectPage stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("分页查询代办消息异常");
        }
        logger.info("分页查询流程代办列表成功======={}",JSONObject.toJSONString(filerList));
        PageResponse pageResponses = new PageResponse();
        pageResponses.setPageSize(Long.parseLong(qry.getPageSize() + ""));
        pageResponses.setPageNum(Long.parseLong(qry.getPageNum() + ""));
        pageResponses.setSuccess(Boolean.TRUE);
        pageResponses.setData(managerTodoDOS);
        pageResponses.setTotalCount(Long.parseLong(filerList.size() + ""));
        return pageResponses;
    }

    public Date LocalDateToUdate(LocalDate localDate) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
        return Date.from(instant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response update(TasksManagerUpOperatorDTO dto) {
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper<>();
        if (!CollectionUtils.isEmpty(dto.getTaskInstanceIds())) {
            updateWrapper.in("TASK_INSTANCE_ID", dto.getTaskInstanceIds());
        }
        if (!CollectionUtils.isEmpty(dto.getProcessInstanceIds())) {
            updateWrapper.in("PROCESS_INSTANCE_ID", dto.getProcessInstanceIds());
        }
        if (StringUtils.isNotBlank(dto.getOperator())) {
            updateWrapper.eq("OPERATOR", dto.getOperator());
        }
        if (StringUtils.isNotBlank(dto.getOperatorName())) {
            updateWrapper.eq("OPERATOR_NAME", dto.getOperatorName());
        }
        if (StringUtils.isNotBlank(dto.getNewOperator())) {
            tasksManagerTodoDO.setOperator(dto.getNewOperator());
        }
        if (StringUtils.isNotBlank(dto.getNewOperatorName())) {
            tasksManagerTodoDO.setOperatorName(dto.getNewOperatorName());
        }
        if (null != dto.getIsTransfer()) {
            tasksManagerTodoDO.setIsTransfer(dto.getIsTransfer());
        }
        if (null != dto.getIsUrgent()) {
            tasksManagerTodoDO.setIsUrgent(dto.getIsUrgent());
        }
        tasksManagerTodoDO.setUpdateTime(new Date());
        int compatibleCount = 0;
        try {
            tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
            // 处理来自 Flowable 引擎的转办数据
            compatibleCount = flowableTransferCompatible(dto);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("update error msg:" + e.toString());
            logger.error("update stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("更新待办发生异常");
        } catch (Throwable th) {
            throw new BizException("更新待办发生内部错误：" + th.toString());
        }
        logger.info("修改流程代办事项成功=======[{%s}]",JSONObject.toJSONString(tasksManagerTodoDO));
        logger.info("兼容处理 Flowable 转办代办事项条数=======[{%d}]", compatibleCount);
        return Response.buildSuccess();
    }

    /**
     * Flowable 流程引擎在非会签任务的多人审批时，会在待办组件生成多条 task_instance_id 相同的待办任务，
     * 若其中一个用户进行转办操作，则该节点任务变更为转办后的人审批，原来的所有审批人不再拥有审批任务。
     * 只需保留一条newOperator的待办
     *
     * @param dto 请求值
     * @return count 逻辑删除的条数
     */

    private int flowableTransferCompatible(TasksManagerUpOperatorDTO dto) {
        List<Long> deletingIds;
        int count = 0;
        if (null == dto || null == dto.getIsTransfer() || null == dto.getTaskInstanceIds()) {
            return count;
        }
        if (dto.getIsTransfer()) { //
            UpdateWrapper<TasksManagerTodoDO> taskIdsWrapper = new UpdateWrapper<>();
            taskIdsWrapper.in("TASK_INSTANCE_ID", dto.getTaskInstanceIds());
            // task_instance_id 对应的待办记录条数
            Integer recordCount = tasksManagerTodoMapper.selectCount(taskIdsWrapper);
            // 一对多时，对应 Flowable 的待办
            if (recordCount > dto.getTaskInstanceIds().size()) {
                for (String taskId : dto.getTaskInstanceIds()) {
                    UpdateWrapper<TasksManagerTodoDO> taskIdWrapper = new UpdateWrapper<>();
                    taskIdWrapper.eq("TASK_INSTANCE_ID", taskId);
                    if (tasksManagerTodoMapper.selectCount(taskIdWrapper) > 1) {
                        // 一个 taskId 对应多条记录的情况
                        List<TasksManagerTodoDO> tasksManagerTodoDOS = tasksManagerTodoMapper.selectList(taskIdWrapper);
                        List<Long> idList = tasksManagerTodoDOS.stream().map(TasksManagerTodoDO::getId
                        ).collect(Collectors.toList());
                        // 转给 newOperator 的待办只需保留一条（任意一条）
                        deletingIds = idList.subList(0, idList.size() - 1);
                        // 逻辑删除
                        count = tasksManagerTodoMapper.deleteBatchIds(deletingIds);
                        logger.info("处理 Flowable 转办代办事项成功，删除新审批人收到的多余待办条数[{%s}]", count);
                    }
                } //
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateECTime(TasksManagerUpECTimeDTO dto) {
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper<>();
        int count = 0;
        if (StringUtils.isNotBlank(dto.getTaskInstanceId())) {
            updateWrapper.eq("TASK_INSTANCE_ID", dto.getTaskInstanceId());
        }
        tasksManagerTodoDO.setUpdateTime(new Date());
        tasksManagerTodoDO.setExpectedCompletionTime(DateUtil.parseDateTime(dto.getExpectedCompletionTime()));
        try {
            count = tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("updateTime error msg:" + e.toString());
            logger.error("updateTime stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("更新待办应完时间发生异常");
        }
        logger.info("修改流程代办应完时间成功=======[%s],更新条数[%d]",JSONObject.toJSONString(tasksManagerTodoDO), count);
        return Response.buildSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateTaskType(TasksManagerUpTaskTypeDTO dto){
        TasksManagerTodoDO tasksManagerTodoDO = new TasksManagerTodoDO();
        UpdateWrapper<TasksManagerTodoDO> updateWrapper = new UpdateWrapper<>();
        int count = 0;
        if (StringUtils.isNotBlank(dto.getProcessCode())) {
            updateWrapper.eq("PROCESS_CODE", dto.getProcessCode());
        }
        if (StringUtils.isNotBlank(dto.getNodeCode())) {
            updateWrapper.eq("NODE_CODE", dto.getNodeCode());
        }
        tasksManagerTodoDO.setTaskType(dto.getTaskType());
        try {
            count = tasksManagerTodoMapper.update(tasksManagerTodoDO, updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("updateTaskType error stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("更新待办任务类型异常！");
        }
        logger.info("更新待办任务类型成功=======[%s],更新条数[%d]",JSONObject.toJSONString(tasksManagerTodoDO), count);
        return Response.buildSuccess();
    }
    @Override
    public SingleResponse<TasksManagerVO> selectDetailsById(TasksManagerDetailsQry detailsQry) {
        TasksManagerTodoDO managerDO = tasksManagerTodoMapper.selectById(detailsQry.getId());
        if (null == managerDO) {
            throw new BizException("根据待办id:" + detailsQry.getId() + ",未查询到数据");
        }
        TasksManagerVO tasksManagerVO = new TasksManagerVO();
        BeanUtils.copyProperties(managerDO, tasksManagerVO);
        tasksManagerVO.setId(managerDO.getId() + "");
        tasksManagerVO.setFieldArea((Map) JSON.parse(managerDO.getFieldArea()));
        if (StringUtils.isNotBlank(managerDO.getStatus())) {
            String statusType = DealTypeEnum.getType(managerDO.getStatus());
            tasksManagerVO.setStatus(statusType);
        }
        logger.info("查询代办详情成功=======:"+ tasksManagerVO);
        return SingleResponse.of(tasksManagerVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response delete(TasksManagerDelDTO tasksManagerDelDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!CollectionUtils.isEmpty(tasksManagerDelDTO.getTaskInstanceIds())) {
            queryWrapper.in("TASK_INSTANCE_ID", tasksManagerDelDTO.getTaskInstanceIds());
        }
        if (StringUtils.isNotBlank(tasksManagerDelDTO.getCreator())) {
            queryWrapper.eq("CREATOR", tasksManagerDelDTO.getCreator());
        }
        if (StringUtils.isNotBlank(tasksManagerDelDTO.getSourceApplicationNum())) {
            queryWrapper.eq("SOURCE_APPLICATION_NUM", tasksManagerDelDTO.getSourceApplicationNum());
        }
        if (!CollectionUtils.isEmpty(tasksManagerDelDTO.getProcessInstanceIds())) {
            queryWrapper.in("PROCESS_INSTANCE_ID", tasksManagerDelDTO.getProcessInstanceIds());
        }
        if (StringUtils.isNotBlank(tasksManagerDelDTO.getOperator())) {
            queryWrapper.eq("OPERATOR", tasksManagerDelDTO.getOperator());
        }
        if (StringUtils.isNotBlank(tasksManagerDelDTO.getOperatorName())) {
            queryWrapper.eq("OPERATOR_NAME", tasksManagerDelDTO.getOperatorName());
        }
        try {
            tasksManagerTodoMapper.delete(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("del error msg:" + e.toString());
            logger.error("del stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("删除代办异常");
        }
        logger.info("删除代办成功==============");
        return Response.buildSuccess();
    }

    /**
     * 生成id
     *
     * @return
     */
    private Long genId() {
        String format = DateUtil.format(new Date(), "yyMMddHHmmssSSSSS");
        String formatted = String.format("%04d", new Random().nextInt(10000));
        return Long.parseLong(format);
    }


}
